// login.js
const app = getApp();

Page({
  data: {
    phone: '',
    password: '',
    showPassword: false,
    rememberPassword: false,
    canLogin: false
  },

  onLoad: function() {
    // 检查是否有记住的密码
    this.checkRememberedPassword();
  },

  // 检查是否有记住的密码
  checkRememberedPassword: function() {
    const savedPhone = wx.getStorageSync('rememberedPhone');
    const savedPassword = wx.getStorageSync('rememberedPassword');
    
    if (savedPhone && savedPassword) {
      this.setData({
        phone: savedPhone,
        password: savedPassword,
        rememberPassword: true
      });
      this.validateForm();
    }
  },

  // 手机号输入
  onPhoneInput: function(e) {
    this.setData({
      phone: e.detail.value
    });
    this.validateForm();
  },

  // 密码输入
  onPasswordInput: function(e) {
    this.setData({
      password: e.detail.value
    });
    this.validateForm();
  },

  // 切换密码可见性
  togglePasswordVisibility: function() {
    this.setData({
      showPassword: !this.data.showPassword
    });
  },

  // 切换记住密码
  toggleRemember: function() {
    this.setData({
      rememberPassword: !this.data.rememberPassword
    });
  },

  // 验证表单
  validateForm: function() {
    const phone = this.data.phone;
    const password = this.data.password;
    
    // 简单验证：手机号11位，密码至少6位
    const isValidPhone = /^1[3-9]\d{9}$/.test(phone);
    const isValidPassword = password.length >= 6;
    
    this.setData({
      canLogin: isValidPhone && isValidPassword
    });
  },

  // 登录
  login: function() {
    const { phone, password, rememberPassword } = this.data;
    
    wx.showLoading({
      title: '登录中...',
    });
    
    // 模拟登录请求
    setTimeout(() => {
      wx.hideLoading();
      
      // 模拟成功响应
      const mockUserInfo = {
        nickName: '美食爱好者',
        avatarUrl: '../../images/default-avatar.png',
        phone: phone,
        level: '普通用户',
        memberDays: 0
      };
      
      // 保存登录状态
      wx.setStorageSync('userInfo', mockUserInfo);
      wx.setStorageSync('token', 'mock-token-' + Date.now());
      
      // 如果需要记住密码
      if (rememberPassword) {
        wx.setStorageSync('rememberedPhone', phone);
        wx.setStorageSync('rememberedPassword', password);
      } else {
        wx.removeStorageSync('rememberedPhone');
        wx.removeStorageSync('rememberedPassword');
      }
      
      wx.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          setTimeout(() => {
            // 跳转回上一页或首页
            const pages = getCurrentPages();
            if (pages.length > 1) {
              wx.navigateBack();
            } else {
              wx.switchTab({
                url: '/pages/index/index'
              });
            }
          }, 1500);
        }
      });
    }, 1500);
  },

  // 微信登录
  wechatLogin: function() {
    wx.showLoading({
      title: '登录中...',
    });
    
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        const userInfo = res.userInfo;
        
        wx.login({
          success: (loginRes) => {
            if (loginRes.code) {
              // 这里应该发送code到服务器换取openid等信息
              // 现在模拟登录成功
              setTimeout(() => {
                wx.hideLoading();
                
                // 保存登录状态
                userInfo.level = '普通用户';
                userInfo.memberDays = 0;
                
                wx.setStorageSync('userInfo', userInfo);
                wx.setStorageSync('token', 'mock-wechat-token-' + Date.now());
                
                wx.showToast({
                  title: '登录成功',
                  icon: 'success',
                  duration: 1500,
                  success: () => {
                    setTimeout(() => {
                      // 跳转回上一页或首页
                      const pages = getCurrentPages();
                      if (pages.length > 1) {
                        wx.navigateBack();
                      } else {
                        wx.switchTab({
                          url: '/pages/index/index'
                        });
                      }
                    }, 1500);
                  }
                });
              }, 1500);
            } else {
              wx.hideLoading();
              wx.showToast({
                title: '登录失败',
                icon: 'none'
              });
            }
          },
          fail: () => {
            wx.hideLoading();
            wx.showToast({
              title: '登录失败',
              icon: 'none'
            });
          }
        });
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '请授权后登录',
          icon: 'none'
        });
      }
    });
  },

  // 注册
  register: function() {
    wx.navigateTo({
      url: '/pages/register/register'
    });
  },

  // 忘记密码
  forgotPassword: function() {
    wx.navigateTo({
      url: '/pages/forgot-password/forgot-password'
    });
  },

  // 显示用户协议
  showUserAgreement: function() {
    wx.showModal({
      title: '用户协议',
      content: '欢迎使用美食管家！\n\n用户协议内容...',
      showCancel: false,
      confirmText: '我知道了'
    });
  },

  // 显示隐私政策
  showPrivacyPolicy: function() {
    wx.showModal({
      title: '隐私政策',
      content: '保护您的隐私是我们的责任！\n\n隐私政策内容...',
      showCancel: false,
      confirmText: '我知道了'
    });
  }
})